import React, { useContext } from 'react';
import { Table, Tag, Tooltip } from 'antd';
import { trim } from 'lodash';
import classnames from 'classnames';

import Pre from '@/components/Pre';

import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';
import { getRangeDescription } from '@/pages/SalaryManage/SalaryCalculate/InsuranceFundFile/rangeDescription';

import BaseSettingContext from './BaseSettingContext';
import style from './index.less';

const STATUS = {
    NORMAL: 0,
    DELETE: 1,
    ADD: 2,
    EDIT: 3
};
const MODIFY_STATUS = {
    // 正常
    [STATUS.NORMAL]: {
        tag: null,
        rowTheme: null
    },
    // 删除
    [STATUS.DELETE]: {
        tag: {
            text: '删除',
            color: 'red'
        },
        rowTheme: 'delete'
    },
    // 新增
    [STATUS.ADD]: {
        tag: {
            text: '新增',
            color: 'cyan'
        },
        rowTheme: 'add'
    },
    // 编辑
    [STATUS.EDIT]: {
        tag: {
            text: '编辑',
            color: 'blue'
        },
        rowTheme: null
    }
};

const onFieldCell = field => record =>
    record?.[field] === 1 ? { 'data-cell-theme': 'modified' } : { 'data-cell-theme': '' };

const wrapperWithRowSpan = (children, record) => ({
    children,
    props: {
        rowSpan: record.v_rowSpan
    }
});

const ShareToolTip = ({ title, children }) => (
    <Tooltip
        title={
            <div style={{ textAlign: 'center' }}>
                <Pre>{title}</Pre>
            </div>
        }
        overlayStyle={{ maxWidth: 'fit-content' }}
    >
        <div>{children}</div>
    </Tooltip>
);

const FormulaDescription = ({ text }) => {
    const descList = trim(text)
        .split('\r\n')
        // eslint-disable-next-line react/no-array-index-key
        .map((item, index) => <div key={item + index} className={style.formulaItem}>{item}</div>);

    return (<div className={style.formulaDescription}>{descList}</div>);
};

/**
 * 表格列定义
 * @returns []
 */
const tableColumn = showCompareEffect => [
    {
        title: '雇员年龄（X）',
        dataIndex: 'vv_age_range',
        width: 142,
        render: (text, record) => {
            const { startAgeSign, endAgeSign } = record;
            const startAge = trim(record.startAge);
            const endAge = trim(record.endAge);

            return wrapperWithRowSpan(
                <EmptyPlaceHolder value={getRangeDescription(startAge, startAgeSign, endAge, endAgeSign)} />,
                record
            );
        },
        ellipsis: true
    },
    {
        title: '雇员该自然月薪资总额',
        dataIndex: 'vv_month_total',
        width: 185,
        render: (text, record) => {
            // 由于后台是新增的也返回了数据，但是左边表格又不能显示，这样特殊处理实属无奈
            if (!showCompareEffect && record.rowStatus === STATUS.ADD) {
                return <EmptyPlaceHolder />;
            }
            const statusMapperInfo = MODIFY_STATUS[record.rowStatus] ?? MODIFY_STATUS[STATUS.NORMAL];
            const tagInfo = showCompareEffect ? statusMapperInfo.tag : MODIFY_STATUS[STATUS.NORMAL];

            const { twStartAmtSign, twEndAmtSign } = record;
            const twStartAmt = trim(record.twStartAmt);
            const twEndAmt = trim(record.twEndAmt);

            return (
                <div>
                    <EmptyPlaceHolder
                        value={getRangeDescription(twStartAmt, twStartAmtSign, twEndAmt, twEndAmtSign, '$')}
                    />
                    {tagInfo ? <Tag color={tagInfo.color} className={style.ml8}>{tagInfo.text}</Tag> : null}
                </div>
            );
        },
        ellipsis: true
    },
    {
        title: '总的公积金缴交比例（雇员+雇主）',
        dataIndex: 'totalShare',
        onCell: onFieldCell('totalShareStatus'),
        ellipsis: true,
        render(text, record) {
            // 由于后台是新增的也返回了数据，但是左边表格又不能显示，这样特殊处理实属无奈
            if (!showCompareEffect && record.rowStatus === STATUS.ADD) {
                return <div className={style.formulaDescription}><EmptyPlaceHolder /></div>;
            }
            return (
                <ShareToolTip title={text}>
                    <FormulaDescription text={text} />
                </ShareToolTip>
            );
        }
    },
    {
        title: '雇员公积金缴交比例',
        dataIndex: 'employeeShare',
        onCell: onFieldCell('employeeShareStatus'),
        ellipsis: true,
        render(text, record) {
            // 由于后台是新增的也返回了数据，但是左边表格又不能显示，这样特殊处理实属无奈
            if (!showCompareEffect && record.rowStatus === STATUS.ADD) {
                return <div className={style.formulaDescription}><EmptyPlaceHolder /></div>;
            }

            return (
                <ShareToolTip title={text}>
                    <FormulaDescription text={text} />
                </ShareToolTip>
            );
        }
    },
    {
        title: '雇主公积金缴交比例',
        dataIndex: 'companyShare',
        onCell: onFieldCell('companyShareStatus'),
        render(text, record) {
            // 由于后台是新增的也返回了数据，但是左边表格又不能显示，这样特殊处理实属无奈
            if (!showCompareEffect && record.rowStatus === STATUS.ADD) {
                return <div className={style.formulaDescription}><EmptyPlaceHolder /></div>;
            }

            return (
                <ShareToolTip title={text}>
                    <FormulaDescription text={text} />
                </ShareToolTip>
            );
        }
    }
];

const getGroupKey = item => `${item?.startAge}_${item?.startAgeSign}_${item?.endAge}_${item?.endAgeSign}`;

const wrapDataSource = dataList => {
    if (!dataList || dataList.length === 0) {
        return [];
    }

    const result = [];
    dataList.forEach((detail, ind) => {
        const { startAge, startAgeSign, endAge, endAgeSign, rows } = detail;
        if (rows?.length > 0) {
            rows.forEach((share, index) => {
                result.push({
                    vvId: `vvId_${ind}_${index}`,
                    ...share,
                    startAge,
                    startAgeSign,
                    endAge,
                    endAgeSign,
                    v_rowSpan: index === 0 ? rows.length : 0
                });
            });
        }
    });

    return result;
};

const TableWrapper = ({
    columns,
    dataSource,
    showCompareEffect,
    comparePosition,
    hoverRow,
    selectedRow,
    setCurrentHoverRow,
    setCurrentSelectedRow
}) => {
    const tableProps = {
        onRow: record => ({
            className: classnames({
                'row-hover': hoverRow && getGroupKey(hoverRow.row) === getGroupKey(record),
                'row-cell-hover': hoverRow && hoverRow.row.vvId === record.vvId,
                'row-selected': selectedRow && selectedRow.row.vvId === record.vvId
            }),
            onClick: () => {
                setCurrentSelectedRow({ position: comparePosition, row: record });
            },
            onMouseEnter: () => {
                setCurrentHoverRow({ position: comparePosition, row: record });
            },
            onMouseLeave: () => {
                setCurrentHoverRow(null);
            },
            'data-row-theme': showCompareEffect
                ? (MODIFY_STATUS[record?.rowStatus] || MODIFY_STATUS['0'])?.rowTheme || ''
                : ''
        })
    };

    return (
        <div>
            <Table
                size="small"
                tableLayout="fixed"
                columns={columns}
                rowKey="vvId"
                dataSource={dataSource}
                pagination={false}
                scroll={{ x: 'max-content' }}
                bordered
                {...tableProps}
            />
        </div>
    );
};

const CompareItem = ({
    dataSource,
    showCompareEffect = false,
    comparePosition,
    hoverRow,
    selectedRow,
    setCurrentHoverRow,
    setCurrentSelectedRow
}) => {
    const {
        contextState: { scale = 2 }
    } = useContext(BaseSettingContext);
    return (
        <div className="compare-item">
            <TableWrapper
                columns={tableColumn(showCompareEffect, scale)}
                dataSource={wrapDataSource(dataSource)}
                showCompareEffect={showCompareEffect}
                pagination={false}
                comparePosition={comparePosition}
                hoverRow={hoverRow}
                selectedRow={selectedRow}
                setCurrentHoverRow={setCurrentHoverRow}
                setCurrentSelectedRow={setCurrentSelectedRow}
            />
        </div>
    );
};

export default CompareItem;
